/**
 * 实现狼容器
 * 创建者：Carburn Ashroom
 * 2024.1.2
 */

package Char;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class WolfCreator implements WolfCreatorConfig {

    private int progress = 0;
    private final Point pos = new Point();
    private final Dimension screen;
    private final int wolfHeight;
    private final ArrayList<Wolf> wolves = new ArrayList<>();
    private final BufferedImage wolfBuffer;

    public WolfCreator(Dimension scrnSize) throws IOException {
        screen = scrnSize;
        wolfBuffer = ImageIO.read(new File(Wolf.DIR));
        wolfHeight = WIDTH * wolfBuffer.getHeight() / wolfBuffer.getWidth();
        randomPos();
    }

    public boolean update(Sheep sheep) throws IOException {     // 更新状态并返回是否有狼追上了小羊
        if (++progress == CREATE_TIME) {
            progress = 0;
            wolves.add(new Wolf(pos, WIDTH, screen));
            randomPos();
        }
        for (Wolf w : wolves) {
            w.update(sheep);
            if (w.intersects(sheep)) {
                return true;
            }
        }
        return false;
    }

    private void randomPos() {      // 随机生成坐标
        pos.x = (int) (Math.random()*(screen.width-WIDTH));
        pos.y = (int) (Math.random()*(screen.height-wolfHeight));
    }

    public void draw(BufferedImage frame) {     // 绘制
        Graphics2D g = (Graphics2D) frame.getGraphics();
        int height = progress * wolfBuffer.getHeight() / CREATE_TIME;
        int drawHeight = progress * wolfHeight / CREATE_TIME;
        g.drawImage(wolfBuffer.getSubimage(0, 0, wolfBuffer.getWidth(), height+1), pos.x, pos.y, WIDTH, drawHeight, null);
        for (Wolf w : wolves) {
            w.draw(frame);
        }
    }

}